package Thread;
class MyBlockingQueue{
    Object locker = new Object();
    private  String[] arr = null;
    //队首
    private  int front =0;
    //队尾
    private  int rear = 0;
    //元素个数
    private  int size = 0;
    public MyBlockingQueue(int capacity){
        arr = new String[capacity];
    }
    public  void  put(String elem) throws InterruptedException {
        synchronized (locker){
            while (size>=arr.length){
                //队列满了，需要阻塞
                //return;
                locker.wait();
            }
            arr[rear] = elem;
            rear++;
            if(rear>=arr.length){
                rear = 0;
            }
            // tail = (tail + 1) % data.length;
            size++;
            locker.notify();
        }
    }
    public  String take() throws InterruptedException {
        synchronized (locker){
            while ( size==0){
                //队列空，需要阻塞
                //return null;
                locker.wait();
            }
            String ret = arr[front];
            front++;
            if (front>=arr.length){
                front =0;
            }
            size--;
            locker.notify();
            return ret;
        }
    }
}
public class Demo28 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        String str = "小野猫一边在回复那些平台推的信息，一边在等待我的信息，我猜想她可能不在乎，但是也有可能在想我" ;
        Thread producer = new Thread(()->{
           while (true){
               try {
                   queue.put(str+" ");
                   System.out.println("这是生成者说出的话："+str);
                   String str1 = str;
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });
        Thread consumer = new Thread(()->{
           String str1 =str;
           while (true){
               try {
                   queue.take();
                   System.out.println("消费者购买的元素:"+str);
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });
        producer.start();
        consumer.start();
    }
}
